<script setup>
import axios from "axios";
import { ref, watch } from "vue";
const props = defineProps({
	list: {
		type: Array,
		default: () => [],
	},
});

const fileList = ref([]);
const picList = ref([]);

const afterRead = (file) => {
	const params = new FormData();

	if (Object.prototype.toString.call(file).match(/ (\S*)]/)[1] === "Array") {
		file.forEach((item) => params.append("files", item.file));
	} else {
		params.append("files", file.file);
	}
	axios.post("/dingdong/api/ddys/file/ossUpload", params).then((res) => {
		if (res.code === 200) {
			picList.value = [...picList.value, ...res.data];
		}
	});
	console.log(params);
	// 上传请求
};

const onDelete = (e, val) => {
	picList.value.splice(val.index, 1);
};

const emit = defineEmits(["update:list"]);
watch(
	[props.list, picList],
	([newValue1, newValue2], oldValue) => {
		if (newValue1.length > newValue2.length) {
			picList.value = newValue1;
			fileList.value = newValue1.map((item) => {
				return { url: item };
			});
		}
		if (newValue1.length < newValue2.length) {
			emit("update:list", newValue2);
		}
	},
	{ immediate: true },
);
</script>

<template>
	<van-uploader v-model="fileList" multiple :after-read="afterRead" @delete="onDelete" />
</template>

<style lang="scss">
.van-uploader {
	display: block;
	.van-uploader__wrapper {
		display: grid;
		grid-template-columns: repeat(4, 1fr);
		grid-column-gap: 10px;
		grid-row-gap: 10px;
		place-items: center;
		.van-uploader__preview {
			margin: 0;
			overflow: hidden;
			border-radius: 6px;
			.van-image {
				width: 72px;
				height: 72px;
			}
		}
		.van-uploader__upload {
			width: 72px;
			height: 72px;
			margin: 0;
			border: 1px dashed #dcdee0;
			border-radius: 6px;
			overflow: hidden;
		}
	}
}
</style>
